/*
 * Copyright (c) 2008-2018, RF-Embedded GmbH
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 *  1. Redistributions of source code must retain the above copyright notice, 
 *     this list of conditions and the following disclaimer.
 *  2. Redistributions in binary form must reproduce the above copyright notice, 
 *     this list of conditions and the following disclaimer in the 
 *     documentation and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES 
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT 
 * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT 
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR 
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.IO.Ports;
using System.Net.Sockets;
using System.IO;
using System.Net;


namespace CSrfeReaderInterface.impl.device
{
    /// <summary>
    /// Implementation of a TCP device
    /// </summary>
    public class TCPDevice : CSrfeReaderInterface.device.IProtocolDeviceInterface
    {
        Socket _tcpClient;
        IPAddress _ipAddress;
        Int32 _port;
        Thread _receiveThread;

        bool _terminate;
        
        /// <summary>
        /// Constructs a new TCP device
        /// </summary>
        /// <param name="host">IP address of the reader</param>
        /// <param name="port">Port of the reader</param>
        public TCPDevice(IPAddress host, int port)
        {   
            IPEndPoint endpoint = new IPEndPoint(host, port);
            _tcpClient = new Socket(endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
           
            //Create a thread which executes the ReceiveData-method defined below
            _receiveThread = new Thread(new ThreadStart(ReceiveData));
            //Terminate flag for thread
            _terminate = false;

            this._ipAddress = host;
            this._port = port;
        }

        /// <summary>
        /// IP address of the tcp port
        /// </summary>
        /// <returns>The currently used IP address</returns>
        public string IpAddress()
        {
            return _ipAddress.ToString();
        }

        /// <summary>
        /// Port number of the tcp port
        /// </summary>
        /// <returns>The currently used port number</returns>
        public Int32 Port()
        {
            return _port;
        }

        /// <summary>
        /// Sends byte data through the given tcp socket
        /// </summary>
        /// <param name="data">The data to send</param>
        /// <returns>Success of the operation</returns>
        public override bool Send(byte[] data)
        {
            try
            {
                _tcpClient.Send(data);
            }
            catch (Exception /*exception*/)
            {
                return false;
            }
            return true;

        }


        /// <summary>
        /// Method should be called by a thread
        /// </summary>
        private void ReceiveData()
        {            
            while (!_terminate)
            {
                try
                {
                    if (_tcpClient.Available > 0)
                    {
                        byte[] buf = new byte[_tcpClient.Available];

                        _tcpClient.Receive(buf);

                        //report read event
                        RaiseDataReadEvent(buf);
                    }
                }
                catch (Exception /*exception*/)
                {
                    
                }

                Thread.Sleep(10);
            }
        }

        /// <summary>
        /// Opens the connection to the reader.
        /// </summary>
        /// <returns>Success of the operation</returns>
        public override bool Open()
        {
            try
            {
                //Connect tcp socket
                _tcpClient.Connect(_ipAddress, _port);
                _terminate = false;
                //On successful connection start receiver thread
                if (_tcpClient.Connected)
                    _receiveThread.Start();
            }
            catch (SocketException /*socketException*/)
            {
                _terminate = true;
                return false;
            }

            return _tcpClient.Connected;
        }

        /// <summary>
        /// Closes the connection to the reader.
        /// </summary>
        /// <returns>Success of the operation</returns>
        public override bool Close()
        {     
            _terminate = true;

            _tcpClient.Close();
            return !(_tcpClient.Connected);
        }
    }
}
